package cn.addr.user.service;

import java.util.List;
import java.util.UUID;

import org.hibernate.Query;
import org.junit.Test;

import cn.addr.user.dao.UserDao;
import cn.addr.user.model.LinkPerson;
import cn.addr.user.model.UserBean;

public class UserCRUD {
	private static UserDao userDao = UserDao.getInstance();
	
	/**注册
	 */
	public boolean register(UserBean user){
		String uuid = UUID.randomUUID().toString();
		if(login(user)!=null)
			return false;
		else{
			user.setUuid(uuid);
			try {
				userDao.begin();
				userDao.save(user);
				userDao.commit();
			} catch (Exception e) {
				userDao.rollback();
			}finally{
				userDao.close();
			}
			return true;			
		}
	}
	
	@SuppressWarnings("unchecked")
	public UserBean login(UserBean user){
		List<UserBean> result = null;
		String username = user.getUsername();
		String password = user.getPassword();
		System.out.println(user);
		String hql = "FROM UserBean where username = ? and password = ?";
		try {
			userDao.begin();
			Query query = userDao.createQuery(hql);
			query.setParameter(0, username);
			query.setParameter(1, password);
			System.out.println(hql);
			result = query.list();
			userDao.commit();
			if(!result.isEmpty()){
				return result.get(0);
			}
		} catch (Exception e) {
			System.out.println(11111);
			userDao.rollback();
			e.printStackTrace();
		}finally{
			userDao.close();
		}
		return null;
	}
	
//	/**添加联系人
//	 */
//	@Test
//	public void addLinkPerson(){
//		UserBean user1 = new UserBean("kong","123");
//		Tag tag = new Tag();
//		LinkPerson e = new LinkPerson("lai", "697773", "763741198@qq.com", "http://localhost",
//				new Date(), "1.1.1.1", "scau", "TaiShan", "510410",  "2B");
//		tag.setTagname("friend");
//		e.getTaglist().add(tag);
//		user1.getLinkPersons().add(e);
//		this.register(user1);
//	}
	

	@Test
	public void getAll(){
		Long i = (long) 1;
		userDao.begin();
		UserBean ub = userDao.get(i);
		for(LinkPerson c : ub.getLinkPersons()){
			System.out.println(c);			
		}
		userDao.commit();
		userDao.close();
		
		char s = 'a';
		switch (s) {
		case 'A':
			
			break;

		default:
			break;
		}
		
	}
}

